<template>
  <div>
    <el-card class="box-card">
      <el-row>
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">系统管理</el-breadcrumb-item>
          <el-breadcrumb-item>商品资料管理</el-breadcrumb-item>
        </el-breadcrumb>
      </el-row>
      <el-row><br></el-row>
      <el-row>
        <el-col :span="24">
          <el-form :inline="true" :model="dto" label-width="100px" class="form-inline" size="small" ref="dtoForm" :rules="dtoRules">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="dto.name" placeholder="请输入商品名称"></el-input>
            </el-form-item>
            <el-form-item label="商品编号" prop="no">
              <el-input v-model="dto.no" placeholder="请输入商品编号"></el-input>
            </el-form-item>
            <el-form-item label="商品类别" prop="categoryId">
              <el-cascader
                v-model="dto.categoryId"
                clearable
                :options="categoryList"></el-cascader>
            </el-form-item>
            <el-form-item label="商品单位" prop="unitId">
              <el-select v-model="dto.unitId" clearable placeholder="请选择">
                <el-option
                  v-for="item in unitList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品供应商" prop="supplierId">
              <el-select v-model="dto.supplierId" clearable placeholder="请选择">
                <el-option
                  v-for="item in supplierList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品状态" prop="status">
              <el-select v-model="dto.status" clearable placeholder="请选择">
                <el-option label="启用" value="1"></el-option>
                <el-option label="停用" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品售价≥" prop="salePrice">
              <el-input v-model="dto.salePrice" placeholder="请输入商品售价"></el-input>
            </el-form-item>
            <el-form-item label="商品库存≥" prop="stock">
              <el-input v-model="dto.stock" placeholder="请输入商品库存"></el-input>
            </el-form-item>
            <el-form-item label="商品级别" prop="type">
              <el-select v-model="dto.type" clearable placeholder="请选择">
                <el-option label="成品" value="成品"></el-option>
                <el-option label="次品" value="次品"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-button type="primary" icon="el-icon-search" @click="getProductList('dtoForm')">查询</el-button>
          <el-button type="warning" @click="resetForm('dtoForm')">清空</el-button>
          <el-button type="success" round @click="HandleAdd()">添 加 商 品</el-button>
        </el-col>
      </el-row>
      <el-row><br></el-row>
      <el-row>
        <el-table
          :data="productList"
          style="width: 100%">
          <el-table-column
            fixed
            label="序号"
            type="index"
            width="50">
          </el-table-column>
          <el-table-column
            fixed
            prop="name"
            label="商品名称"
            width="100">
          </el-table-column>
          <el-table-column
            prop="unit.name"
            label="单位"
            width="50">
          </el-table-column>
          <el-table-column
            prop="no"
            label="编号"
            width="120">
          </el-table-column>
          <el-table-column
            prop="attritionRate"
            label="损耗率"
            width="70">
          </el-table-column>
          <el-table-column
            prop="category.name"
            label="类别"
            width="80">
          </el-table-column>
          <el-table-column
            prop="unitWeight.name"
            label="分量单位"
            width="80">
          </el-table-column>
          <el-table-column
            prop="convert"
            label="换算比"
            width="80">
          </el-table-column>
          <el-table-column
            prop="supplier.name"
            label="供应商"
            width="120">
          </el-table-column>
          <el-table-column
            label="图片"
            width="100">
            <template slot-scope="scope">
              <img :src="scope.row.pic" alt="" style="width: 80px;height: 80px;">
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
            width="50">
            <template slot-scope="scope">
              <span style="color: green;" v-if="scope.row.status == 1">启用</span>
              <span style="color: red;" v-else>停用</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="240">
            <template slot-scope="scope">
              <el-button
                size="mini" type="primary" icon="el-icon-edit"
                @click="handleEdit(scope.row)">编辑</el-button>
              <el-button
                size="mini" v-if="scope.row.status == 1" type="warning"
                @click="handleDisable(scope.row)">停用</el-button>
              <el-button
                size="mini" v-if="scope.row.status == 0" type="success"
                @click="handleEnable(scope.row)">启用</el-button>
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            @current-change="handleCurrentChange"
            :current-page.sync="dto.page"
            :page-size="5"
            layout="total, prev, pager, next"
            :total="total">
          </el-pagination>
      </el-row>
      <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="closeDialog('ruleForm')">
        <el-form :model="product" :rules="rules" ref="ruleForm">
          <el-form-item label="商品名称" :label-width="formLabelWidth" prop="name">
            <el-input v-model="product.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品单位" :label-width="formLabelWidth" prop="unitId">
            <el-select v-model="product.unitId"  clearable placeholder="请选择"
            @change="handleChange1">
              <el-option
                v-for="item in unitList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="分量单位" :label-width="formLabelWidth" prop="unitWeightId">
            <el-select v-model="product.unitWeightId"  clearable placeholder="请选择" @change="handleChange2">
              <el-option
                v-for="item in unitList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="换算比商品:分量" :label-width="formLabelWidth" prop="convert">
            <el-input v-model="product.convert" :disabled="true" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品类别" :label-width="formLabelWidth" prop="categoryId">
            <el-cascader
              v-model="product.categoryId"
              clearable
              :props="{ value: 'value',label: 'label',children: 'children'}"
              :options="categoryList"></el-cascader>
          </el-form-item>
          <el-form-item label="商品供应商" :label-width="formLabelWidth" prop="supplierId">
            <el-select v-model="product.supplierId"  clearable placeholder="请选择">
              <el-option
                v-for="item in supplierList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="图片" :label-width="formLabelWidth" prop="pic">
            <el-upload
              class="avatar-uploader"
              :action="action"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess">
              <el-image v-if="imageUrl !=''" :src="imageUrl" class="avatar" fit="fill"></el-image>
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品描述" :label-width="formLabelWidth" prop="description">
            <el-input
              type="textarea"
              :autosize="{ minRows: 2}"
              placeholder="请输入内容"
              v-model="product.description">
            </el-input>
          </el-form-item>
          <el-form-item label="商品售价" :label-width="formLabelWidth" prop="salePrice">
            <el-input v-model="product.salePrice" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="库存上限" :label-width="formLabelWidth" prop="stockUpperLimit">
            <el-input v-model="product.stockUpperLimit" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="库存下限" :label-width="formLabelWidth" prop="stockLowerLimit">
            <el-input v-model="product.stockLowerLimit" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品级别" :label-width="formLabelWidth" prop="type">
            <el-select v-model="product.type" placeholder="请选择">
              <el-option label="成品" value="成品"></el-option>
              <el-option label="次品" value="次品" disabled></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeDialog('ruleForm')">取 消</el-button>
          <el-button type="primary" @click="handleSubmit('ruleForm')">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import cookieUtil from '@/util/cookie';
export default {
  data() {
    var compareLimit = (rule, value, callback) => {
      if (this.product.stockLowerLimit != "" && this.product.stockUpperLimit != "") {
        if (this.product.stockLowerLimit >= this.product.stockUpperLimit) {
          callback(new Error('库存上限要大于库存下限'));
        }else{
          callback();
        }
      }
    }
    return {
      action:"api/file/upload",
      headers:{
        Authorization: "Bearer " + cookieUtil.getCookie("authorization"),
        refresh: cookieUtil.getCookie("refresh")
      },
      dto:{
        name:"",
        no:"",
        categoryId:"",
        unitId:"",
        supplierId:"",
        status:"",
        salePrice:"",
        stock:"",
        type:"",
        page:1,
        size:5
      },
      total:"",
      categoryList:[],
      unitList:[],
      supplierList:[],
      productList:[],
      title:"",
      dialogFormVisible:false,
      product:{
        name:"",
        categoryId:"",
        unitWeightId:"",
        convert:"",
        unitId:"",
        supplierId:"",
        pic:"",
        description:"",
        salePrice:"",
        stockUpperLimit:"",
        stockLowerLimit:"",
        type:""
      },
      formLabelWidth:"150px",
      unit1:{
        id:"",
        weight:""
      },
      unit2:{
        id:"",
        weight:""
      },
      imageUrl:'',
      rules:{
        name:[
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        unitId:[
          { required: true, message: '请选择商品单位', trigger: 'change' },
        ],
        unitWeightId:[
          { required: true, message: '请选择商品单位', trigger: 'change' },
        ],
        categoryId:[
          { required: true, message: '请选择商品类别', trigger: 'change' },
        ],
        supplierId:[
          { required: true, message: '请选择商品供应商', trigger: 'change' },
        ],
        pic:[
          { required: true, message: '请上传商品图片', trigger: 'change' },
        ],
        description:[
          { required: true, message: '请输入商品描述', trigger: 'blur' },
        ],
        salePrice:[
          { required: true, message: '请输入商品售价', trigger: 'blur' },
          {pattern:/^\d{1,10}(?:\.\d{1,3})?$/,message: '请输入非负数字(小数点后最多保留三位)', trigger: 'blur' },
        ],
        stockUpperLimit:[
          { required: true, message: '请输入库存上限', trigger: 'blur' },
          {pattern:/^\d{1,10}(?:\.\d{1,3})?$/,message: '请输入非负数字(小数点后最多保留三位)', trigger: 'blur' },
          { validator: compareLimit , trigger: 'blur' }
        ],
        stockLowerLimit:[
          { required: true, message: '请输入库存下限', trigger: 'blur' },
          {pattern:/^\d{1,10}(?:\.\d{1,3})?$/,message: '请输入非负数字(小数点后最多保留三位)', trigger: 'blur' },
          { validator: compareLimit , trigger: 'blur' }
        ],
        type:[
          { required: true, message: '请选择商品级别', trigger: 'change' },
        ]
      },
      dtoRules:{
        salePrice:[
          {pattern:/^\d{1,10}(?:\.\d{1,3})?$/,message: '请输入非负数字(小数点后最多保留三位)', trigger: 'blur' },
        ],
        stock:[
          {pattern:/^\d{1,10}(?:\.\d{1,3})?$/,message: '请输入非负数字(小数点后最多保留三位)', trigger: 'blur' },
        ],
      }
    }
  },
  mounted() {
    this.getAllCategory()
    this.getAllUnit()
    this.getAllSupplier()
    this.getProductList('dtoForm')
  },
  methods:{
    //获取所有可用类别
    getAllCategory(){
      this.$axios.get('/category/getAllCategory').then(res=>{
        if (res.data.code == 200) {
          let list = res.data.data
          for (const c of list) {
            if(c.pid == 0){
              let category = {
                value: c.id,
                label: c.name,
                children: []
              }
              for (const c1 of list) {
                if(c1.pid == c.id){
                  let category1 = {
                    value: c1.id,
                    label: c1.name,
                  }
                  category.children.push(category1)
                }
              }
              this.categoryList.push(category)
            }
          }
        }
      })
    },
    //获取所有可用单位
    getAllUnit(){
      this.$axios.get('/unit/getAllUnit').then(res=>{
        if (res.data.code == 200) {
          this.unitList = res.data.data
        }
      })
    },
    //获取所有可用供应商
    getAllSupplier(){
      this.$axios.get('/supplier/getAllSupplier').then(res=>{
        if (res.data.code == 200) {
          this.supplierList = res.data.data
        }
      })
    },
    //重置查询表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleCurrentChange(val){
      this.dto.page = val
      this.getProductList('dtoForm')
    },
    //获取产品列表
    getProductList(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.get('/product/getProductList',{
            params:{
              name: this.dto.name,
              no: this.dto.no,
              categoryId: this.dto.categoryId[1],
              unitId: this.dto.unitId,
              supplierId: this.dto.supplierId,
              status: this.dto.status,
              salePrice: this.dto.salePrice,
              stock: this.dto.stock,
              type: this.dto.type,
              page: this.dto.page,
              size: this.dto.size
            }}).then(res=>{
            if (res.data.code == 200) {
              this.productList = res.data.data.data
              this.total = res.data.data.total
            }
          })
        } else {
          return false;
        }
      });
    },
    //点击添加产品按钮
    HandleAdd(){
      this.title = "添加商品"
      this.product = {
        name:"",
        categoryId:"",
        unitWeightId:"",
        convert:"",
        unitId:"",
        supplierId:"",
        pic:"",
        description:"",
        salePrice:"",
        stockUpperLimit:"",
        stockLowerLimit:"",
        type:""
      }
      this.imageUrl=""
      this.dialogFormVisible = true
    },
    //更改商品单位
    handleChange1(val){
      for (const unit of this.unitList) {
        if (unit.id == val) {
          this.unit1 = unit
          break
        }
      }
      if (this.unit2.id !== "") {
        this.getConvert()
      }
    },
    //更改分量单位
    handleChange2(val){
      for (const unit of this.unitList) {
        if (unit.id == val) {
          this.unit2 = unit
          break
        }
      }
      if (this.unit1.id !== "") {
        this.getConvert()
      }
    },
    //获取换算比
    getConvert(){
      this.product.convert = (this.unit2.weight / this.unit1.weight).toFixed(3)
    },
    //上传图片成功
    handleAvatarSuccess(res, file) {
      this.product.pic = file.response.data
      this.imageUrl = file.response.data
    },
    closeDialog(formName){
      this.$refs[formName].clearValidate();
      this.dialogFormVisible = false
    },
    handleSubmit(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let product = this.product
          product.categoryId = this.product.categoryId[1]
          if (this.title == "添加商品") {
            this.$axios.post("/product/addProduct",product).then(res=>{
              if (res.data.code == 200) {
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                });
                this.getProductList('dtoForm')
                this.dialogFormVisible = false
              }
            })
          }      
          if (this.title == "编辑商品") {
            this.$axios.put("/product/updateProduct",product).then(res=>{
              if (res.data.code == 200) {
                this.$message({
                  type: 'success',
                  message: '编辑成功!'
                });
                this.getProductList('dtoForm')
                this.dialogFormVisible = false
              }
            })
          }
        } else {
          return false;
        }
      });
    },
    //打开编辑商品的窗口
    handleEdit(row){
      this.title = "编辑商品"
      this.dialogFormVisible = true
      this.$axios.get('/product/getProductById/' + row.id).then(res=>{
        this.product = res.data.data
        this.imageUrl = this.product.pic
        for (const category of this.categoryList) {
          for (const child of category.children) {
            if (this.product.categoryId == child.value) {
              let list = [] 
              list.push(category.value)
              list.push(child.value)
              this.product.categoryId = list
              break
            }
          }
        }
      })
    },
    //启用商品
    handleEnable(row){
      this.$axios.put('/product/enableProduct/' + row.id).then(res=>{
        if (res.data.code == 200) {
          this.$message({
            type: 'success',
            message: '启用成功!'
          });
          this.getProductList('dtoForm')
        }
      })
    },
    //禁用商品
    handleDisable(row){
      this.$axios.put('/product/disableProduct/' + row.id).then(res=>{
        if (res.data.code == 200) {
          this.$message({
            type: 'success',
            message: '禁用成功!'
          });
          this.getProductList('dtoForm')
        }
        if(res.data.code == 500){
            this.$message.error(res.data.message + '禁用失败！');
          }
      })
    },
    //删除商品
    handleDelete(row){
      this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete('/product/deleteProduct/' + row.id).then(res=>{
          if (res.data.code == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getProductList('dtoForm') 
          }
          if(res.data.code == 500){
            this.$message.error(res.data.message + '删除失败！');
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
  }
}
</script>
<style scoped>
.box-card {
  height: auto;
}
.el-dialog .el-form-item {
  text-align: left;
  width: 70%;
}
.el-form-item {
  text-align: left;
  width: 31%;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>